﻿using System;
using System.ComponentModel;
using XCI.Core;
using XCI.Sys.Forms;
using XCI.Sys.Model;
using XCI.Sys.Service;
using XCI.Windows.Controls;
using XCI.Windows.Extensions;
using XCI.Windows.Helper;

namespace XCI.Sys.Controls
{
    public partial class RecordHistoryGridUserControl : BaseXtraUserControl
    {
        private GridHelper<SysHistory> helper;
        private string _primaryKey;
        private static readonly PageList<SysHistory> nullData = new PageList<SysHistory>();

        public RecordHistoryGridUserControl()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 数据加载
        /// </summary>
        /// <param name="pageIndex">页码</param>
        private void LoadData(int? pageIndex = null)
        {
            if (string.IsNullOrEmpty(_primaryKey))
            {
                helper.SetDataSource(nullData);
                return;
            }

            helper.SetPageIndex(pageIndex);
            var paged = helper.Paged;

            helper.RunCallback(e => { e.Result = HistoryService.Instance.SelectByPrimaryKey(paged, _primaryKey) ?? nullData; })
                .RunAsync();
        }

        /// <summary>
        /// 记录主键
        /// </summary>
        [Category("XCI")]
        [Description("记录主键")]
        [DefaultValue(null)]
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public string PrimaryKey
        {
            get => _primaryKey;
            set
            {
                _primaryKey = value;
                if (helper == null)
                {
                    helper = new GridHelper<SysHistory>(gridView1);
                }

                LoadData(1);
            }
        }

        private void GridView1_DoubleClick(object sender, EventArgs e)
        {
            helper.DblClickRow(e, () =>
            {
                new FrmHistoryDetails(helper).ShowDialogOk();
            });
        }

        private void GridPager1_PageChanged(object sender, Windows.PagerEventArgs e)
        {
            LoadData();
        }
    }
}
